#pragma once

#include "Thread.hpp"
#include "LockGuard.hpp"
#include <iostream>
#include <functional>
#include <vector>
#include <queue>
#include <unistd.h>
#include "Log.hpp"

using namespace Thread;
using namespace log_ns;

const static int defaultnum = 5;

void test(const std::string &name)
{
    while (1)
    {
        sleep(1);
        std::cout << name << ", hello test!" << std::endl;
    }
}
template <class T>
class ThreadPool
{
private:
    void LockQueue()
    {
        pthread_mutex_lock(&_mutex);
    }

    void UnlockQueue()
    {
        pthread_mutex_unlock(&_mutex);
    }

    void WakeUp()
    {
        pthread_cond_signal(&_cond);
    }

    void WakeUpAll()
    {
        pthread_cond_broadcast(&_cond);
    }

    bool IsEmpty()
    {
        return _task_queue.empty();
    }

    void Sleep()
    {
        pthread_cond_wait(&_cond, &_mutex);
    }

    void Hanler(const std::string &name)
    {
        while (1)
        {
            LockQueue();

            while (IsEmpty() && _isRunning)
            {
                // 任务队列为空且线程池不想退出，线程休眠
                _sleep_thread_num++;
                LOG(INFO, "%s thread sleep begin!\n", name.c_str());
                Sleep();
                LOG(INFO, "%s thread wake up!\n", name.c_str());
                _sleep_thread_num--; // 醒来，计数--
            }

            // 判断线程池停止
            if (IsEmpty() && !_isRunning)
            {
                // 任务队列为空且线程池想退出
                UnlockQueue();
                LOG(INFO, "%s thread quit\n", name.c_str());
                break;
            }

            // 到这里一定有任务，取任务
            T task = _task_queue.front();
            _task_queue.pop();
            UnlockQueue();

            // 在锁外执行任务
            task();
            // LOG(INFO, "%s handler task: %s\n", name.c_str(), task.PrintRet().c_str());
        }
    }

    ThreadPool(int thread_num = defaultnum)
        : _thread_num(thread_num), _isRunning(false), _sleep_thread_num(0)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_cond, nullptr);
    }

    // ban 掉拷贝构造和拷贝赋值
    ThreadPool(const ThreadPool<T> &) = delete;
    ThreadPool<T> operator=(const ThreadPool<T> &) = delete;

    void Init()
    {
        for (int i = 0; i < _thread_num; i++)
        {
            func_t func = std::bind(&ThreadPool::Hanler, this, std::placeholders::_1);
            std::string name = "thread-" + std::to_string(i + 1);
            _threads.emplace_back(name, func);
            LOG(DEBUG, "construct thread %s done, init success\n", name.c_str());
        }
    }

    void Start()
    {
        _isRunning = true;

        for (auto &thread : _threads)
        {
            LOG(DEBUG, "start thread %s done.\n", thread.Name().c_str());
            thread.Start();
        }
    }

public:
    ~ThreadPool()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_cond);
    }

    void Equeue(const T &in)
    {
        LockQueue();

        _task_queue.push(in);
        if (_sleep_thread_num > 0)
            WakeUp();
        UnlockQueue();
    }

    void Stop()
    {
        LockQueue();

        _isRunning = false;
        WakeUpAll();

        UnlockQueue();
        LOG(INFO, "Thread Pool Stop Success!\n");
    }

    static ThreadPool<T> *GetInstance()
    {
        // 懒汉
        if (_tp == nullptr)
        {
            LockGuard lock(&_sig_mutex);
            if (_tp == nullptr)
            {
                // 第一次获取
                _tp = new ThreadPool();
                _tp->Init();
                _tp->Start();
                LOG(INFO, "create threadpool\n");
            }
            else
            {
                LOG(INFO, "get threadpool\n");
            }
        }
        return _tp;
    }

private:
    std::vector<thread> _threads; // 管理线程
    int _thread_num;              // 线程数量
    std::queue<T> _task_queue;    // 任务队列

    bool _isRunning;       // 线程池运行状态
    int _sleep_thread_num; // 休眠线程数量

    pthread_mutex_t _mutex;
    pthread_cond_t _cond;

    // 单例模式-懒汉
    static ThreadPool<T> *_tp;
    static pthread_mutex_t _sig_mutex;
};

// 初始化
template <class T>
ThreadPool<T> *ThreadPool<T>::_tp = nullptr;
template <class T>
pthread_mutex_t ThreadPool<T>::_sig_mutex = PTHREAD_MUTEX_INITIALIZER;